import { messages } from "share/common";
import React from 'react'
import { connect } from 'react-redux'
import { Button, Badge, Table, Icon } from 'antd'
import BasicInfo from 'components/basic-info'
import menuRoute from 'routes/menuRoute'
import { setStandardRulesGroup, setExpenseTypeRules } from 'actions/setting'
import expenseStandardService from 'containers/expense-reimbursement-control/expense-standard/expense-standard.service'
import constants from 'share/constants'
import SlideFrame from 'components/slide-frame'
import NewRule from 'containers/expense-reimbursement-control/expense-standard/reimbursement-standard/new-rule'

class ExpenseRules extends React.Component{
  constructor(props) {
    super(props);
    this.state = {
      nowData: {},
      showSlideFrame: false,
      loading: false,
      columns: [
        {title: '管控项', dataIndex: 'messageKey', render: this.getMessageKey},
        {title: '取值方式', dataIndex: 'restriction',
          render: restriction => constants.getTextByValue(restriction, 'restrictions')},
        {title: '条件内容', dataIndex: 'ruleContent', render: this.renderRuleContent},
        {title: '操作', dataIndex: 'operate', render: (text, record) => (
          <span>
            {record.ruleDataType !== 'EXPENSE_LEVEL' &&
            <a onClick={() => this.setState({ showSlideFrame: true, nowData: record })}>编辑</a>}
             <span className="ant-divider" />
            <a>删除</a>
          </span>)
        }
      ],
      data: {},
      pullData: [],
      infoList: [
        {type: 'input', label: '费用类型名称', id: 'expenseTypeName'},
        {type: 'input', label: '规则名称', id: 'ruleName'},
        {type: 'input', label: '控制方式', id: 'actionType'},
        {type: 'input', label: '币种', id: 'currencyCode'},
      ],
      itemData: []
    }
  }

  getMessageKey = messageKey => {
    const { pullData } = this.state;
    let result = '';
    pullData.map(item => {
      item.messageKey === messageKey && (result = item.name)
    });
    return result;
  };

  componentDidMount(){
    let ruleOID = this.props.params.ruleOID;
    const { expenseTypeRules } = this.props;
    if(!expenseTypeRules.id){
      let tempExpenseTypeRules = {
        id: '1034342205726870124',
        code: 'DEFAULT_SOBEXP0050',
        name: '中控测试费用标准',
        iconURL: 'https://huilianyi-static.oss-cn-shanghai.aliyuncs.com//cf2b3694-b4f8-4aca-b233-111748eb025b/expenseIcon/e547b892-8f48-498f-8ecf-90ee3fb5fcf3-door.png',
        categoryName: '费用大类',
        apportionEnabled: true,
        enabled: true,
        expenseTypeOID: 'f2e1379a-4f4a-4c78-b04e-1667b635095e'
      };
      this.props.dispatch(setExpenseTypeRules(tempExpenseTypeRules));
    }
    this.getData(ruleOID);
  }

  getData = ruleOID => {
    this.setState({ loading: true });
    expenseStandardService.getConditions(ruleOID).then(res => {
      let data = res.data;
      expenseStandardService.getPullData(data.entityOID).then(pullDataRes => {
        const { expenseTypeRules, language } = this.props;
        data.expenseTypeName = expenseTypeRules.name;
        let services = [];
        let itemData = [];
        data.conditions.map((item, index) => {
          if(item.ruleDataType === 'COST_DEPARTMENT'){
            itemData.push({
              index,
              key: 'departmentOID',
              label: 'path'
            });
            services.push(expenseStandardService.getDepartment());
          }
          if(item.ruleDataType === 'COST_CENTER'){
            itemData.push({
              index,
              key: 'id',
              label: 'name'
            });
            services.push(expenseStandardService.getCostCenterItems(item.messageKey))
          }
          if(item.ruleDataType === 'USER_GROUP'){
            itemData.push({
              index,
              key: 'id',
              label: 'name'
            });
            services.push(expenseStandardService.getUserGroup())
          }
          if(item.ruleDataType === 'LOCATION_COUNTRY'){
            itemData.push({
              index,
              key: 'code',
              label: 'country'
            });
            services.push(expenseStandardService.getCountry(language.code))
          }
          if(item.ruleDataType === 'LOCATION_GROUP'){
            itemData.push({
              index,
              key: 'id',
              label: 'levelName'
            });
            services.push(expenseStandardService.getCityGroup())
          }
        });
        Promise.all(services).then(res => {
          itemData.map((item, itemIndex) => {
            let ruleContent = [];
            let values = data.conditions[item.index].ruleContent.split(',');
            values.map(value => {
              res[itemIndex].data.map(content => {
                if(content[item.key] === value){
                  ruleContent.push(content)
                }
              })
            });
            data.conditions[item.index].ruleContent = ruleContent;
          });
          this.setState({
            data,
            pullData: pullDataRes.data,
            loading: false,
            itemData
          })
        })
      })
    });
  };

  renderRuleContent = (ruleContent, record, index) => {
    const { itemData } = this.state;
    let target = ruleContent;
    itemData.map(item => {
      if(item.index === index)
        target = ruleContent.map(content => content[item.label]).join(',');
    });
    return target;
  };

  handleClose = flag => {
    let ruleOID = this.props.params.ruleOID;
    this.setState({ showSlideFrame: false });
    if(flag){
      this.getData(ruleOID);
    }
  };

  render() {
    const { data, columns, infoList, loading, showSlideFrame, nowData, pullData } = this.state;
    return (
      <div>
        <BasicInfo infoList={infoList}
                   infoData={data}
                   isHideEditBtn/>
        <div style={{ margin: '30px 0 10px 0' }}>
          <Button type="primary" onClick={() => this.setState({ showSlideFrame: true, nowData: {} })}>
            <Icon type="plus" />&nbsp;新建条件
          </Button>
        </div>
        <Table dataSource={data.conditions}
               columns={columns}
               rowKey="id"
               loading={loading}/>
        <SlideFrame show={showSlideFrame}
                    content={NewRule}
                    onClose={() => this.setState({ showSlideFrame: false })}
                    params={{
                      nowData,
                      pullData,
                      showSlideFrame,
                      data
                    }}
                    afterClose={this.handleClose}
                    title="条件"/>
      </div>
    )
  }
}

ExpenseRules.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    expenseTypeRules: state.setting.expenseTypeRules,
    language: state.main.language
  }
}

export default connect(mapStateToProps)(ExpenseRules)
